package cn.harry.modular.sms.service.impl;

import cn.harry.common.exception.ApiException;
import cn.harry.modular.sms.config.property.AliyunSmsProperties;
import cn.harry.modular.sms.exception.enums.SmsExceptionEnum;
import cn.harry.modular.sms.param.SmsParam;
import cn.harry.modular.sms.service.SmsService;
import cn.harry.modular.sms.service.SmsStrategy;
import cn.hutool.json.JSONUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author harry
 * @公众号 Harry技术
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {

    private final SmsStrategy smsStrategy;
    private final AliyunSmsProperties aliyunSmsProperties;

    @Override
    public String sendSmsCode(String mobile, String templateCode, String msgCode) {
        SmsParam.SmsParamBuilder smsParam = SmsParam.builder().mobile(mobile)
                .templateCode(templateCode)
                // 获取验证码 默认CODE
                .param("code", msgCode);
        sendSms(smsParam.build());
        return aliyunSmsProperties.getEnable() ? "0" : msgCode;
    }


    @Override
    public Boolean sendSms(SmsParam smsParam) {
        log.info("发送短信开始：{}", JSONUtil.toJsonStr(smsParam));

        String templateCode = smsParam.getTemplateCode();
        if (templateCode == null) {
            throw new ApiException(SmsExceptionEnum.TEMPLATE_CODE_ERROR);
        }
        // 调用第三方发送短信
        SendSmsResponse sendSmsResponse = smsStrategy.send(smsParam);
        log.info("发送短信完成：{}", JSONUtil.toJsonStr(sendSmsResponse));
        // 记录短信日志
        return true;
    }

}
